#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class ELSBump2dCheck(CheckBase):
    def __init__(self):
        super(ELSBump2dCheck, self).__init__()
        pass

    def bump2d_check(self):
        problem_bump2d_nodes = []
        for bump_node in cmds.ls(type="bump2d"):
            bumpInterp_index = cmds.getAttr(bump_node + ".bumpInterp")
            if bumpInterp_index == 1:
                problem_bump2d_nodes.append(bump_node)
        return problem_bump2d_nodes

    def check(self):
        problem_bump2d_nodes = self.bump2d_check()
        if problem_bump2d_nodes:
            result_log = u'Error:以下bump2d的use as属性不匹配: %s\n' % problem_bump2d_nodes
        else:
            result_log = u'Succeed:没有问题\n'
        return result_log

    def replace_bump2d_with_normalMap(self, bump2d_node):
        # Create aiNormalMap node
        import mtoa.core as core
        aiNormalMap_node = core.createArnoldNode("aiNormalMap")

        bumpValue_connection_plugin = cmds.listConnections(bump2d_node + ".bumpValue", p=1)
        if bumpValue_connection_plugin:
            bumpValue_connection_plugin = bumpValue_connection_plugin[0]
            source_node = cmds.listConnections(bump2d_node + ".bumpValue", s=1)[0]
            cmds.disconnectAttr(bumpValue_connection_plugin, bump2d_node + ".bumpValue")
            cmds.connectAttr(source_node + ".outColor", aiNormalMap_node + ".input")
        outNormal_connection_plugin = cmds.listConnections(bump2d_node + ".outNormal", p=1)
        if outNormal_connection_plugin:
            outNormal_connection_plugin = outNormal_connection_plugin[0]
            destination_node = cmds.listConnections(bump2d_node + ".outNormal", d=1)[0]
            cmds.disconnectAttr(bump2d_node + ".outNormal", outNormal_connection_plugin)
            cmds.connectAttr(aiNormalMap_node + ".outValue", destination_node + ".normalCamera")
        cmds.delete(bump2d_node)

    def fix(self):
        problem_bump2d_nodes = self.bump2d_check()
        fix_failed_nodes = []
        if problem_bump2d_nodes:
            for bump2d_node in problem_bump2d_nodes:
                try:
                    self.replace_bump2d_with_normalMap(bump2d_node)
                except:
                    fix_failed_nodes.append(bump2d_node)
            if not fix_failed_nodes:
                result_log = u'Succeed:替换成功\n'
                return result_log
            else:
                return u'Error:%s替换失败\n' % fix_failed_nodes

        else:
            return u'Succeed:没有问题'

